package com.jwdf.uda.ui.fragment.home;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.databinding.FragmentHomeBinding;
import com.jwdf.uda.databinding.ViewHomeHeaderBinding;
import com.jwdf.uda.event.IndividualEvent;
import com.jwdf.uda.event.ReplyDetailEvent;
import com.jwdf.uda.event.ReplyDetailItemClickEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.HomeInfoAction;
import com.jwdf.uda.http.action.HomeRecommendListAction;
import com.jwdf.uda.ui.activity.NewProblemsActivity;
import com.jwdf.uda.ui.activity.QuizQuickActivity;
import com.jwdf.uda.ui.activity.SearchActivity;
import com.jwdf.uda.ui.adapter.GenericQuizAdapter;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.utils.AppBus;
import com.jwdf.uda.utils.DisplayUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.NETUtils;
import com.jwdf.uda.utils.PromptUtil;
import com.jwdf.uda.view.XListView;
import com.jwdf.uda.view.banner.Banner;
import com.jwdf.uda.view.prompt.NewHomePrompt;
import com.squareup.otto.Subscribe;
import retrofit2.Response;

/**
 * Created by RD-001 on 2016/4/27.
 */
public class HomeFragment extends BaseFragment {
    private BannerAdapter mBannerAdapter;
    private GenericQuizAdapter mHomeAdapter;
    private FragmentHomeBinding mDataBinding;
    private Banner mBanner;

    public static HomeFragment instance() {
        HomeFragment view = new HomeFragment();
        return view;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mDataBinding = FragmentHomeBinding.inflate(inflater, container, false);
        RelativeLayout.LayoutParams flParams = (RelativeLayout.LayoutParams) mDataBinding.lySearch.getRoot().getLayoutParams();
        flParams.height += DisplayUtils.getStatusBarHeight(getContext());
        mDataBinding.lySearch.getRoot().setLayoutParams(flParams);
        mDataBinding.lySearch.getRoot().setPadding(0, DisplayUtils.getStatusBarHeight(getContext()), 0, 0);
        initHeaderView(inflater);
        requestRecommends(true);
        return mDataBinding.getRoot();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mDataBinding.setHome(this);
        EventBusUtil.registerEvent(this);
        AppBus.getInstance().register(this);
    }

    public void onEvent(IndividualEvent event) {
        requestRecommends(true);
    }

    private void requestRecommends(final boolean refresh) {
        if (refresh && mHomeAdapter.isEmpty()) {
            showLoadingPage(R.id.rl_loading);
        }
        onNewRequestCall(HomeInfoAction.newInstance(getContext()).request(new AHttpService.IResCallback<PbBean.PbResPageGetHomeInfo>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResPageGetHomeInfo> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
                    //                    if(HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                    //                        mDataBinding.homeListView.stopRefresh();
                    //                        mDataBinding.homeListView.stopLoadMore();
                    //                        return;
                    //                    }
                    if (response != null) {
                        doSuccessResponse(refresh, response.body());
                    } else {
                        if (resultCode != AHttpService.IResCallback.RESULT_OK && !NETUtils.isNetworkConnected(getContext())) {
                            showLoadingPage(R.id.rl_loading);
                            setLoadFailedMessage(R.string.loading_failed_message);
                            mDataBinding.homeListView.stopRefresh();
                            mDataBinding.homeListView.stopLoadMore();
                        }
                    }
                }
            }
        }));
    }

    private void doSuccessResponse(boolean refresh, PbBean.PbResPageGetHomeInfo body) {
        if (body != null) {
            closeLoadingPage();
            if (refresh) {
                mBannerAdapter.setData(body.getBannerListList());
                mHomeAdapter.setData(body.getRecommendListList());
                mDataBinding.homeListView.setPullLoadEnable(body.getRecommendListList().size() == getPageLength());
                mDataBinding.homeListView.stopRefresh();
                mDataBinding.homeListView.stopLoadMore();
            } else {
                loadMoreRecommends(mHomeAdapter.getCount());
            }
        }
    }

    private void loadMoreRecommends(int offset) {
        onNewRequestCall(HomeRecommendListAction.newInstance(getContext(), offset).request(new AHttpService.IResCallback<PbBean.PbResPageGetHomeRecommendList>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResPageGetHomeRecommendList> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
                    if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                        mDataBinding.homeListView.stopRefresh();
                        mDataBinding.homeListView.stopLoadMore();
                        return;
                    }
                    mHomeAdapter.append(response.body().getRecommendListList());
                    mDataBinding.homeListView.setPullLoadEnable(response.body().getRecommendListList().size() == getPageLength());
                    mDataBinding.homeListView.stopRefresh();
                    mDataBinding.homeListView.stopLoadMore();
                }
            }
        }));
    }

    @Override
    protected void onReload(Context context) {
        requestRecommends(true);
    }

    @Override
    public void onResume() {
        super.onResume();
        mBanner.start();
    }

    @Override
    public void onPause() {
        mBanner.stop();
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBusUtil.unregisterEvent(this);
    }

    @Override
    public void onDestroy() {
        EventBusUtil.unregisterEvent(mBannerAdapter);
        //        EventBusUtil.unregisterEvent(mHomeAdapter);
        AppBus.getInstance().unregister(this);
        super.onDestroy();
    }

    public void onEventMainThread(ReplyDetailEvent event) {
//        if (ReplyDetailEvent.EVENT_DO_REPLY_PRAISE == event.getEvent()) {
//            requestRecommends(true);
//        }
    }

    public void onEventMainThread(ReplyDetailItemClickEvent event) {
        if (ReplyDetailItemClickEvent.EVENT_COMMENT_LIKE_CLICK == event.getEvent()) {
            requestRecommends(true);
        }
    }

    @Subscribe
    public void onChanged(Context context) {
        mDataBinding.homeListView.setOnScrollListener(null);
//        mOnIXListener.onRefresh(mDataBinding.homeListView);
        mHomeAdapter.notifyDataSetChanged();
    }

    private Banner createBanner() {
        Banner banner = new Banner(getActivity());
        float ratio = (float) 558 / 1334;
        int maxHeight = (int) (DisplayUtils.getDeviceWidth(getContext()) * ratio + 0.5f);
        banner.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, maxHeight));
        return banner;
    }

    private XListView.IXListViewListener mOnIXListener = new XListView.IXListViewListener() {
        @Override
        public void onRefresh(XListView xListView) {
            requestRecommends(true);
        }

        @Override
        public void onLoadMore(XListView xListView) {
            requestRecommends(false);
        }
    };

    private XListView.OnXScrollListener createOnScrollListener(final ViewHomeHeaderBinding headerBinding) {
        return new XListView.OnXScrollListener() {
            @Override
            public void onXScrolling(View view) {

            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(final AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                final int pos = mDataBinding.homeListView.getHeaderViewsCount();
                final View item = view.getChildAt(pos);
                if (item != null) {
                    if (PromptUtil.getMeasuredHeight(item) > 0) {
                        if (PromptUtil.isShowHomePrompt(getActivity())) {
                            PbBean.PbBaseQuestion bean = (PbBean.PbBaseQuestion) view.getItemAtPosition(pos);
                            new NewHomePrompt(getActivity(), item, headerBinding.getRoot(), bean).show();
                            PromptUtil.setHideHomePrompt(getContext());
                        }
                    }
                }
            }
        };
    }

    private void initHeaderView(LayoutInflater inflater) {
        mBanner = createBanner();
        mBannerAdapter = new BannerAdapter();
        mBanner.setAdapter(mBannerAdapter);
        final ViewHomeHeaderBinding headerBinding = DataBindingUtil.inflate(inflater, R.layout.view_home_header, null, false);

        headerBinding.flAsk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NewProblemsActivity.start(v.getContext());
            }
        });
        headerBinding.flReply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityFromFragment(QuizQuickActivity.class);
            }
        });

        mDataBinding.homeListView.setPullRefreshEnable(true);
        mDataBinding.homeListView.setXListViewListener(mOnIXListener);
        mDataBinding.homeListView.addHeaderView(mBanner);
        mDataBinding.homeListView.addHeaderView(headerBinding.getRoot());
        mHomeAdapter = new GenericQuizAdapter(getActivity());
        mDataBinding.homeListView.setAdapter(mHomeAdapter);

        EventBusUtil.registerEvent(mBannerAdapter);
        mDataBinding.lySearch.flInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityFromFragment(SearchActivity.class);
            }
        });
        //        EventBusUtil.registerEvent(mHomeAdapter);

        if (PromptUtil.isShowHomePrompt(getActivity())) {
            mDataBinding.homeListView.setOnScrollListener(createOnScrollListener(headerBinding));
        }

    }

}
